import os
import Defaults
import json

class JSONLanguageReader:
    def __init__(self):
        self.__builtInRegistry = Defaults.Registry()

    def __object_hook(self, dct):
        if "__language__" in dct:
            return Defaults.Language(dct)
        if "__mode__" in dct:
            return Defaults.Mode(dct)
        if "__buildIn__" in dct:
            name = dct["__buildIn__"]
            return self.__builtInRegistry[name]
        return dct

    def read(self, path):
        return json.load(open(path), object_hook=self.__object_hook)

    def readAll(self):
        languages = []
        for root, dirs, files in os.walk('languages'):
            for file in files:
                name, ext = os.path.splitext(file)
                if ext == ".json":
                    languages.append(self.read(file))
        return languages